<?php

namespace App\Repositories;

use App\Models\WechatUser;
use InfyOm\Generator\Common\BaseRepository as iBaseRepository;

class WechatUserRepository extends iBaseRepository
{
    /**
     * @var array
     */
    protected $fieldSearchable = [
        'nickname',
        'openid',
        'unionid',
        'sex',
        'language',
        'city',
        'province',
        'country',
        'headimgurl',
        'subscribe',
        'subscribe_time',
        'status'
    ];

    /**
     * Configure the Model
     **/
    public function model()
    {
        return WechatUser::class;
    }

    public function saveUser($userInfo)
    {
        $attributes = [
            'nickname' => $userInfo['nickName'],
            'appid' => $userInfo['watermark']['appid'],
            'openid' => $userInfo['openId'],
            'sex' => $userInfo['gender'],
            'city' => $userInfo['city'],
            'province' => $userInfo['province'],
            'country' => $userInfo['country'],
            'headimgurl' => $userInfo['avatarUrl'],
        ];

        $user = WechatUser::firstOrNew(['unionid' => $userInfo['unionId']], $attributes);
        if (isset($user->id))
        {
            $user->unionid = $userInfo['unionId'];
            $user->openid = $userInfo['openId'];
            $user->appid = $userInfo['watermark']['appid'];
        }

        return $user->save();
    }

    public function updateUser($attributes, $id)
    {
        $userInfo = [
            'nickname' => $attributes['nickname'],
            'country' => $attributes['country'],
            'province' => $attributes['province'],
            'city' => $attributes['city'],
            'headimgurl' => $attributes['headimgurl'],
        ];
        return parent::update($userInfo, $id);
    }

    public function getUserByUnionid($unionid)
    {
        return $this->model->where('unionid', $unionid)->first();
    }
}
